const fetch = require('cross-fetch');
const crypto = require('crypto');
const GlobalConfig = require('./storage/config.js');
const apiUrl = '/open-api';
module.exports.request = async function (uri, method, data) {
  const { query, json, company_id } = data.data;
  // console.log('-------------------当前请求的query, json: ', query, json);
  const config = new GlobalConfig(company_id);
  const authInfo = await config.getAuthInfo();
  const params = new URLSearchParams();
  delete data.data.query.sudo;
  Object.entries(query).forEach(([key, value]) => {
    if (uri.includes(`{${key}}`)) {
      uri = uri.replace(`{${key}}`, value);
    } else {
      if (Array.isArray(value)) {
        value.forEach((val) => {
          params.append(`${key}[]`, val);
        });
      } else {
        params.append(key, value);
      }
    }
  });
  params.append('private_token', authInfo.privateKey);
  const apiHost = authInfo.host;
  const url = `${apiHost}${apiUrl}${uri}?${params.toString()}`;
  // const url = `${apiHost}${apiUrl}${uri}}`;


  // console.log(url);
  const headers = {
    Authorization: `token ${authInfo.privateKey}`,
  };
  // console.log('headers: ', headers);
  const resp = await fetch(url, {
    method,
    body: json ? JSON.stringify(json) : undefined,
    headers,
  });
  if (resp.status !== 200) {
    return false;
  }
  const finalRes = await resp.json();
  console.log('-------------接口返回的最终数据resp: ', finalRes);
  return finalRes;
};
